package org.fuys.etp.core.pool.queue;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.reflect.MethodUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @projectName: fuys-etp-final
 * @package: org.fuys.etp.core.pool.queue
 * @className: ResizeableLinkedBlockingQueue
 * @author: WangJing
 * @description: 变长阻塞队列
 * @date: 2025/2/10 21:21
 * @version: 1.0
 */
public class ResizeableLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> {
    //反射设置队列大小
    public static <E> void setCapacity(LinkedBlockingQueue<E> queue, int capacity) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        int oldCapacity = getCapacity(queue);
        FieldUtils.writeField(queue, "capacity", capacity, true);
        int size = queue.size();
        //如果队列中的任务已经达到老队列容量限制，并且新的容量大于队列任务数
        if (size >= oldCapacity && capacity > size) {
            MethodUtils.invokeMethod(queue, true, "signalNotFull");
        }
    }


    private static <E> int getCapacity(LinkedBlockingQueue<E> queue) throws IllegalAccessException {
        return (int) FieldUtils.readField(queue, "capacity", true);
    }
}
